//
//  ComposeViewController.swift
//  weibo1
//
//  Created by changhongliang on 2017/8/11.
//  Copyright © 2017年 richinfo. All rights reserved.
//
//xcode 上移动当前行 option + command + [
//鼠标三击选中当前行
//ESC 显示代码提示菜单
//control + f 前移光标
//control + b 后移光标
//control + p 光标移动到上一行
//control + n 光标移动到下一行
//control + a 光标移动到行首
//control + e 光标移动到行位

import UIKit
import Photos
import Alamofire

class ComposeViewController: UIViewController {
    
    var curve = 0
    var time:Float = -1.0
    var sendThumbnailsImageArray:[UIImage] = [UIImage]()
    var originImageArray:[UIImage] = [UIImage]()
    var selectedIndexArray: [IndexPath] = [IndexPath]()
    var targetVC:PhotoBroswerVC?
    /// 字数最大限制值
    fileprivate var maxCount = 140
    let  cellPading = 5
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置导航栏
        setupNavigation()
        //布局发送界面
        view.addSubview(textView)
        textView.addSubview(photoCollectionView)
        photoCollectionView.dataSource = self
        photoCollectionView.delegate = self
        photoCollectionView.register(photoCell.self, forCellWithReuseIdentifier: "photoCell")
        photoCollectionView.register(photoAddCell.self, forCellWithReuseIdentifier: "photoAddCell")
        view.addSubview(bottomToolBar)
        
        bottomToolBar.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(self.view)
        }
        bottomToolBar.addSubview(tipLabel)
        tipLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(bottomToolBar.snp.top).offset(-10)
            make.right.equalTo(bottomToolBar).offset(-10)
        }
        tipLabel.sizeToFit()
        
        //设置textView的代理
        textView.delegate = self
        addChildViewController(keyboardEmotionVC)
        textView.spellCheckingType = .no
        textView.autocorrectionType = .no
        textView.alwaysBounceVertical = true
        //监听键盘的变化
        NotificationCenter.default.addObserver(self, selector: #selector(ComposeViewController.keyboardWillChange(notify:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ComposeViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        guard  targetVC?.selectedImageArray != nil else {
            textView.becomeFirstResponder()
            return
        }
        if targetVC?.operationID == "nextStepBtnClick" {
            sendThumbnailsImageArray = (targetVC?.selectedImageArray)!
            selectedIndexArray = (targetVC?.selectedIndexArray)!
        }
        //处理发送按钮的问题
        rightButton.backgroundColor =  textView.hasText || selectedIndexArray.count != 0 ?  UIColor.orange : UIColor.white
        rightButton.setTitleColor(textView.hasText || selectedIndexArray.count != 0 ? UIColor.white : UIColor.lightGray, for: .normal)
        //召唤键盘
        if sendThumbnailsImageArray.count == 0 {
            textView.becomeFirstResponder()
          
        }else {
            let  collectionViewPading = 20.0
            let width = UIScreen.main.bounds.width - CGFloat(2.0 * collectionViewPading)
            photoCollectionView.frame = CGRect(x:CGFloat(collectionViewPading), y: 150.0, width: CGFloat(width), height: CGFloat(width))
            photoCollectionView.reloadData()
        }
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //注销键盘
        textView.resignFirstResponder()
    }
    
    
    deinit{
        NotificationCenter.default.removeObserver(self)
    }
    

    //MARK: - 内部控制方法
    @objc private func keyboardWillChange(notify:Notification){
        
        if time == 0 {
            time = (notify.userInfo![UIKeyboardAnimationDurationUserInfoKey]! as AnyObject).floatValue
        }
        if curve == 0 {
            curve = (notify.userInfo![UIKeyboardAnimationCurveUserInfoKey]! as AnyObject).intValue
        }
        
        //1.取出键盘的frame
        let rect = (notify.userInfo![UIKeyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue
        UIView.animate(withDuration: TimeInterval(time)) {
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: self.curve)!)
            self.bottomToolBar.transform = CGAffineTransform(translationX: 0, y: -(rect?.size.height)!);
        }

    }
    
    
    @objc private func keyboardWillHide(notification : Notification){
        UIView.animate(withDuration: TimeInterval(time)) {
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: self.curve)!)
            self.bottomToolBar.transform = CGAffineTransform.identity
        }
    }
    
    
    func setupNavigation(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftButton)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.isEnabled = false
        let titleView = UIView()
        let titleToplabel = UILabel(title: "发微博")
        titleToplabel.textColor = UIColor.black
        titleView.addSubview(titleToplabel)
        titleToplabel.snp.makeConstraints { (make) in
            make.top.centerX.equalTo(titleView)
        }
        titleToplabel.sizeToFit()
        
        let titleBottomLabel = UILabel(title:"三十七度的温暖")
        titleBottomLabel.textColor = UIColor.gray
        titleView.addSubview(titleBottomLabel)
        titleBottomLabel.snp.makeConstraints { (make) in
            make.centerX.bottom.equalTo(titleView)
            make.top.equalTo(titleToplabel.snp.bottom).offset(2)
        }
        titleBottomLabel.sizeToFit()
        let width = max(titleToplabel.frame.size.width,titleBottomLabel.frame.size.width )
        navigationItem.titleView = titleView
        titleView.snp.makeConstraints { (make) in
            make.width.equalTo(width)
        }
        titleView.sizeToFit()
        //navigationcontroller会调整内部可以滚动的控件的内边距
//        automaticallyAdjustsScrollViewInsets = false
    }
    
    
    func cancleBtnClick(){
        dismiss(animated: true, completion: nil)
    }
    
    
    func sendBtnClick(){
        //1.准备数据
        let text = self.textView.emoticonString()
        let image = sendThumbnailsImageArray.first
        //2.发微博
        var path = "2/statuses/"
        path += "upload.json"
        let parameters = ["access_token": UserAccount.loadUserAccount()!.access_token!, "status": text]
        NetworkTools.upload(URLString: BaseUrl + path, parameters: parameters, text: text, imageArray: [image!]) { (respond, error) in
            print("result:\(String(describing: respond))")
            print("error:\(String(describing: error))")
        }
//        NetworkTools.upload(URLString: BaseUrl + path, text: text, imageArray: [image!]) { (result) in
//            
//        }
//        NetworkTools.upload(URLString: BaseUrl + path, parameters: parameters, text: text, imageArray: [image!]) { (result) in
//            print("result:\(result)---")
//        }
//        Alamofire.upload(
//            multipartFormData: { multipartFormData in
//                // 1.将图片转换为二进制
//                let data = UIImagePNGRepresentation(image!)!
//                multipartFormData.append(data, withName: "helloword.png", mimeType: "image/png")
//                //2.设置请求参数
//                for (key, value) in parameters {
//                    multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
//                }
//        },
//            to: BaseUrl + path,
//            encodingCompletion: { encodingResult in
//                switch encodingResult {
//                case .success(let upload, _, _):
//                    upload.responseJSON { response in
//                        print(response)
//                    }
//                    print("uploadSuccess")
//                case .failure(let encodingError):
//                    print(encodingError)
//                }
//        }
//        )
    
    }
    
    func addBtnClick(){
        let PBVC = PhotoBroswerVC()
        PBVC.selectedImageArray = sendThumbnailsImageArray
        PBVC.selectedIndexArray = selectedIndexArray
        self.present(UINavigationController.init(rootViewController: PBVC), animated: true, completion:nil)
        self.targetVC = PBVC
    }
    
    func removeBtnClick(btn:UIButton){
        sendThumbnailsImageArray.remove(at: btn.tag)
        selectedIndexArray.remove(at: btn.tag)
        photoCollectionView.reloadData()
    }
    
    
    func barButtonClick(barbutton:UIBarButtonItem){
        if barbutton.tag == 3 {
            // 1.关闭键盘
            textView.resignFirstResponder()
            
            // 2切换键盘
            self.textView.inputView = (self.textView.inputView != nil) ? nil : self.keyboardEmotionVC.view
            // 3.重新召唤键盘
            self.textView.becomeFirstResponder()
        }
            
        if barbutton.tag == 0 {
            addBtnClick()
        }
        
    }
    
    func authorize(status: PHAuthorizationStatus = PHPhotoLibrary.authorizationStatus(), completion: @escaping (_ authorized: Bool) -> Void) {
        switch status {
        case .authorized:
            // 授权成功
            completion(true)
        case .notDetermined:
            // 没有申请过权限，开始申请权限
            PHPhotoLibrary.requestAuthorization({ (status) -> Void in
                DispatchQueue.main.async(execute: { () -> Void in
                    self.authorize(status: status, completion: completion)
                })
            })
        default: ()
        // 访问相册被拒绝，提醒用户去设置授权
        DispatchQueue.main.async(execute: { () -> Void in
            completion(false)
        })
        }
    }
    
    
// MARK: - 懒加载
    lazy var textView:ComposeTextView = {
        let textView = ComposeTextView()
        textView.bounces = true
        textView.frame = CGRect(x: 0.0, y: 0.0, width:ScreenWidth, height: ScreenHeight - 64.0)
        textView.font = UIFont.systemFont(ofSize: 15)
        return textView
    }()
    
    
    lazy var keyboardEmotionVC: KeyboardEmoticonViewController = KeyboardEmoticonViewController {[unowned self] (emoticon) in
        self.textView.insertEmoticon(emoticon: emoticon)
//        自己触发方法
        self.textViewDidChange(self.textView)
    }

    
    lazy var bottomToolBar:UIToolbar = {
        let toolBar = UIToolbar()
        let imagenames = ["compose_toolbar_picture",
                          "compose_mentionbutton_background",
                          "compose_trendbutton_background",
                          "compose_emoticonbutton_background",
                          "compose_addbutton_background",
        ]
        var items = [UIBarButtonItem]()
        //添加子控件
        for (index, imagename) in imagenames.enumerated(){
            let imageBarButtonItem = UIBarButtonItem(image: UIImage(named:imagename)?.withRenderingMode(UIImageRenderingMode.alwaysOriginal), style: .plain, target: self, action: #selector(ComposeViewController.barButtonClick(barbutton:)))
            imageBarButtonItem.tag = index
            items.append(imageBarButtonItem)
            if index != imagenames.count - 1{
                let spaceBarItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
                items.append(spaceBarItem)
            }
           
        }
        toolBar.setItems(items, animated: false)
        return toolBar
    }()
    
    
    lazy var leftButton:UIButton = {
        let leftButton = UIButton(title: "取消", color: UIColor.black, imageName: "")
        leftButton.addTarget(self, action: #selector(ComposeViewController.cancleBtnClick), for:UIControlEvents.touchUpInside)
        leftButton.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        return leftButton
    }()
    
    
    lazy var rightButton:UIButton = {
        let rightButton = UIButton(title: "  发送  ", color: UIColor.lightGray, imageName: "")
        rightButton.backgroundColor = UIColor.white
        rightButton.addTarget(self, action: #selector(ComposeViewController.sendBtnClick), for:UIControlEvents.touchUpInside)
        rightButton.frame.size = CGSize(width: 46, height: 22)
        rightButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        return rightButton
    }()
    
    
    lazy var tipLabel:UILabel = {
        let label = UILabel()
        label.textColor = UIColor.gray
        label.font = UIFont.systemFont(ofSize: 14)
        return label
    }()
    
    lazy var photoCollectionView:UICollectionView = {
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: PhotosLayout())
        return collectionView
    }()
}



extension ComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView){
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
        (textView as! ComposeTextView).placeholderLabel.isHidden = textView.hasText
        rightButton.backgroundColor =  textView.hasText || selectedIndexArray.count != 0 ?  UIColor.orange : UIColor.white
        rightButton.setTitleColor(textView.hasText || selectedIndexArray.count != 0 ? UIColor.white : UIColor.lightGray, for: .normal)
        //设置剩余字数
        let count =  (textView as! ComposeTextView).emoticonString().characters.count
        // 2.2设置剩余可以输入的字数
        tipLabel.text = "\(count)"
        //2.3设置文本颜色
        tipLabel.textColor = (count > maxCount) ? UIColor.red : UIColor.black
        
        //处理textview滚动的问题
        let line : CGRect = textView.caretRect(for: (textView.selectedTextRange?.start)!)
//        print("line = \(line)")
        
        let overFlow = line.origin.y + line.size.height - (textView.contentOffset.y + textView.bounds.size.height - textView.contentInset.bottom - textView.contentInset.top - 108.0 )
        
//        print("\n OverFlow = \(overFlow)")
        
        if (0 < overFlow)
        {
            // We are at the bottom of the visible text and introduced a line feed, scroll down (iOS 7 does not do it)
            // Scroll caret to visible area
            
            var offSet : CGPoint = textView.contentOffset
            
//            print("offSet = \(offSet)")
            
            //leave 7 pixels margin
            offSet.y += (overFlow + 7)
            
            //Cannot animate with setContentOffset:animated: or caret will not appear
            
            UIView.animate(withDuration: 0.3, animations: {
                textView.setContentOffset(offSet, animated: true)
            })
        }
        
    }
    
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
            self.textView.resignFirstResponder()
        
    }
    
   
   }

extension ComposeViewController :UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.sendThumbnailsImageArray.count + 1 > 9 ? 9 : self.sendThumbnailsImageArray.count + 1 
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.item < sendThumbnailsImageArray.count {
           let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "photoCell", for: indexPath) as! photoCell
            cell.image = sendThumbnailsImageArray[indexPath.item]
            cell.removeButton.tag = indexPath.item
            cell.removeButton.addTarget(self, action: #selector(ComposeViewController.removeBtnClick(btn:)), for: UIControlEvents.touchUpInside)
            return cell
        }else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "photoAddCell", for: indexPath) as!photoAddCell
            //在哪里添加比较好呢
            cell.removeButton.addTarget(self, action:#selector(ComposeViewController.addBtnClick), for:UIControlEvents.touchUpInside)
           return cell
        }
        
    }


}


class PhotosLayout: UICollectionViewFlowLayout{
        override func prepare() {
            super.prepare()
            //1.计算宽度
            let  collectionViewPading = 20.0
            let  cellPading = 5.0
            let width = UIScreen.main.bounds.width - CGFloat(2.0 * collectionViewPading) - CGFloat(2.0 * cellPading)
            itemSize  = CGSize(width: width/3.0, height: width/3.0)
            minimumInteritemSpacing = 5
            minimumLineSpacing = 5
            scrollDirection = UICollectionViewScrollDirection.vertical
            collectionView?.showsVerticalScrollIndicator = false
            collectionView?.showsHorizontalScrollIndicator = false
            collectionView?.isPagingEnabled = true
            collectionView?.backgroundColor = UIColor.white
            }
}


class photoCell: UICollectionViewCell {
    var image:UIImage?{
        didSet{
            photoImageView.image = image
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.white
        contentView.addSubview(photoImageView)
        photoImageView.contentMode = UIViewContentMode.scaleToFill
       //设置控件尺寸的同时设置边距equalTo(<#T##other: ConstraintRelatableTarget##ConstraintRelatableTarget#>)
        photoImageView.snp.makeConstraints { (make) in
            make.edges.equalTo(UIEdgeInsets.zero)
        }
        photoImageView.backgroundColor = UIColor.random
        
        contentView.addSubview(editLabel)
        editLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(contentView).offset(-2)
            make.left.equalTo(contentView).offset(2)
        }
        editLabel.sizeToFit()
        
        contentView.addSubview(removeButton)
        removeButton.snp.makeConstraints { (make) in
            make.top.equalTo(contentView).offset(2)
            make.right.equalTo(contentView).offset(-2)
        }
        removeButton.sizeToFit()
        
        }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var photoImageView:UIImageView = UIImageView()
    lazy var editLabel:UILabel = {
        let label = UILabel(title: "编辑")
        label.textColor = UIColor.white
        label.font = UIFont.systemFont(ofSize: 10)
        return label
    }()
    
    lazy var removeButton:UIButton = {
        let btn = UIButton(type: UIButtonType.custom)
        btn.setBackgroundImage(UIImage(named:"compose_card_delete_normal-1"), for:.normal)
        btn.setBackgroundImage(UIImage(named:"compose_card_delete_highlighted-1"), for: .highlighted)
        return btn
    }()
}


class photoAddCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.white
        contentView.addSubview(removeButton)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var removeButton:UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named:"compose_pic_add"), for: .normal)
        btn.setBackgroundImage(UIImage(named:"compose_pic_add_highlighted"), for: .highlighted)
        btn.frame = self.contentView.bounds
        return btn
    }()

    
}


